package com.edu.zut.security;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import com.edu.zut.result.HttpCode;
import com.edu.zut.result.ResponseResult;
import com.edu.zut.utils.JwtUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author 许文科
 * @Date 2023/1/13 18:41
 * @Description paperdetect-bcak
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token) || JwtUtil.verify(token) == false) {
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        Map<String, Claim> claimMap = JwtUtil.getClaimsFormToken(token);
//        System.out.println("claimMap" + claimMap);

        if (claimMap == null) {
            throw new RuntimeException("token不合法");
//            return new ResponseResult(HttpCode.BAD_REQUEST,)
        }

        String username = claimMap.get("userName").asString();
        List<String> roleNames = JSON.parseArray(claimMap.get("roleNames").asString(), String.class);

        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String item : roleNames) {
            authorities.add(() -> item);
        }


        //存入SecurityContextHolder
        // 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);

    }
}
